import os

from dotenv import load_dotenv

from ..models.paper_model import Paper
from sqlalchemy.orm import Session
from sqlalchemy import select, update, desc
from fastapi import HTTPException
import random
from ..utils.uploads_oss import main as upload_on_oss

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")
def get_papers(db: Session):
    query = select(Paper).order_by(Paper.id.asc())
    return db.execute(query).scalars().all()


def create_paper(db: Session, name,path,type,subject,grade,starts):
    if db.execute(select(Paper).where(Paper.name ==name)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Paper {name} already exists")
    file_path=os.path.join(SOURCES_PATH, path)
    upload_on_oss(path,file_path)
    new_paper = Paper(name=name,path=path,
                      type=type,subject=subject,
                      grade=grade,starts=starts,
                      oss_url="http://whatteam1.oss-cn-beijing.aliyuncs.com/"+path)
    db.add(new_paper)
    db.commit()
    db.refresh(new_paper)
    return new_paper.as_dict()


def update_paper(db: Session, paper_id, paper_data):
    exist_paper = db.execute(select(Paper).where(Paper.id == paper_id)).scalar()
    if not exist_paper:
        raise HTTPException(status_code=404, detail=f"Paper {paper_id} not found")
    for k, v in paper_data.model_dump().items():
        setattr(exist_paper, k, v)
    db.commit()
    return exist_paper


def delete_paper(db: Session, paper_id):
    exist_paper = db.get(Paper, paper_id)
    if not exist_paper:
        raise HTTPException(status_code=404, detail="Paper not found")
    db.delete(exist_paper)
    db.commit()
    return exist_paper.as_dict()


def check_paper_exists(db: Session, paper_id):
    return db.get(Paper, paper_id) is not None

def get_textbook_page(db:Session,subject: str, page: int = 1, page_size: int = 10):
    try:
        offset = (page - 1) * page_size
        textbook_list = (
            db.query(Paper)
            .filter(Paper.subject == subject)

            .offset(offset)
            .limit(page_size)
            .all()
        )
        return textbook_list
    finally:
        db.close()
def get_paper_by_grade_subject(db: Session, grade: str, subject: str, page: int = 1, page_size: int = 10):
    try:
        offset = (page - 1) * page_size

        # 构建查询
        query = (
            db.query(Paper)
            .filter(Paper.grade == grade)
            .filter(Paper.subject == subject)
            .offset(offset)
            .limit(page_size)
        )

        total_count = query.count()
        total_pages = (total_count + page_size - 1) // page_size  # 向上取整

        # 执行查询并转换为字典列表
        # results = [paper.as_dict() for paper in query.all()]
        results=[]
        for paper in query.all():
            data=paper.as_dict()
            if "副本" in data.get("path"):
                continue
            results.append(data)
        return results, total_pages

    finally:
        db.close()
def get_paper_by_id(db: Session, paper_id):
    result=db.execute(select(Paper).where(Paper.id == paper_id)).scalar()
    if not result:
        return {}
    return result.as_dict()


# if __name__== "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()
    # result = update_paper_path_slashes(db)
    # print(result)
